using System;
using Gtk;
using TwitterLib;
using TwitterLib.Utilities;
using System.Security;
using System.Xml;
using System.Collections.Generic;
using twitalotgtk;
using System.ComponentModel;
using System.Timers;

public partial class MainWindow: Gtk.Window
{	
	string _username = string.Empty;
	SecureString _password = new SecureString();
	
	TwitterNet _twitter = new TwitterNet();
	TweetCollection _tweets = new TweetCollection();
	
	public MainWindow (): base (Gtk.WindowType.Toplevel)
	{
		Build ();
			
		//txtUpdateText.Buffer.Changed += HandleChanged;		
		
		if(System.IO.File.Exists(TweetCollection.SaveFileAbsolutePath))
		{
			_tweets = TweetCollection.LoadFromDisk();
			if(_tweets.Count > 0)
				DisplayTweets(_tweets);
		}
		
		MainClass.Settings.PropertyChanged += HandlePropertyChanged;
		InitSettings();
		ApplySettings();
		
		if(MainClass.Settings.Password != string.Empty)	//they stored their password. Fools! :)
		{
			txtPassword.Text = MainClass.Settings.Password;
			hbLogin.Visible = false;
			Login();
		}
		
		vbMain.Visible = true;
	}
	

	protected override void OnShown ()
	{
		base.OnShown ();
		
		nbTweets.CurrentPage = 0;
	}

	void HandlePropertyChanged(object sender, PropertyChangedEventArgs e)
	{
		ApplySettings();
	}
	
	void InitSettings()
	{
		MainClass.Settings.SuppressPropertyChangedNotification = true; //supress notifcations during initialisation.
		
		//set the colours to system defaults;
		
		if(MainClass.Settings.WindowColour.Equal(Gdk.Color.Zero))
			MainClass.Settings.RowColour = MainClass.Settings.WindowColour = eventbox1.Style.Background(StateType.Normal);
					
		if(MainClass.Settings.InputBackgroundColour.Equal(Gdk.Color.Zero))
			MainClass.Settings.InputBackgroundColour = txtUpdateText.Style.Base(StateType.Normal);
		
		if(MainClass.Settings.InputTextColour.Equal(Gdk.Color.Zero))
			MainClass.Settings.InputTextColour = txtUpdateText.Style.Text(StateType.Normal);
		
		MainClass.Settings.SuppressPropertyChangedNotification = false;	//resume notifications.
	}
	
	void ApplySettings()
	{
		txtUsername.Text = MainClass.Settings.Username;		
		
		//if the colours haven't been set, then just use system defaults.
		
		if(!MainClass.Settings.WindowColour.Equal(Gdk.Color.Zero))
			eventbox1.ModifyBg(StateType.Normal, MainClass.Settings.WindowColour);
		
		if(!MainClass.Settings.InputBackgroundColour.Equal(Gdk.Color.Zero))
		{
			
			txtUpdateText.ModifyBase(StateType.Normal, MainClass.Settings.InputBackgroundColour);
			txtPassword.ModifyBase(StateType.Normal, MainClass.Settings.InputBackgroundColour);
			txtUsername.ModifyBase(StateType.Normal, MainClass.Settings.InputBackgroundColour);
		}
		
		if(!MainClass.Settings.InputTextColour.Equal(Gdk.Color.Zero))
		{
			txtUpdateText.ModifyText(StateType.Normal, MainClass.Settings.InputTextColour);		
			txtPassword.ModifyText(StateType.Normal, MainClass.Settings.InputTextColour);		
			txtUsername.ModifyText(StateType.Normal, MainClass.Settings.InputTextColour);
		}
	}
	
	void HandleChanged(object sender, EventArgs e)
	{
		int length = ((Gtk.TextBuffer)sender).Text.Trim().Length;
		btnUpdate.Label = string.Format("{0} ({1})", btnUpdate.Label, length.ToString());
		
		if(length > 140)
			btnUpdate.Label = string.Format("{0}*", btnUpdate.Label);
	}
	
	protected void OnDeleteEvent (object sender, DeleteEventArgs a)
	{
		Application.Quit ();
		a.RetVal = true;
	}

	protected virtual void btnUpdate_Clicked (object sender, System.EventArgs e)
	{		
		_twitter.AddTweet(txtUpdateText.Buffer.Text.Trim());
	}

	protected virtual void btnlogin_clicked (object sender, System.EventArgs e)
	{
		Login();
	}
	
	private void Login()
	{
		_username = txtUsername.Text;
		_password = TwitterNet.ToSecureString(txtPassword.Text);
		
		if(MainClass.Settings.StorePassword)
			MainClass.Settings.Password = txtPassword.Text;	//PLAIN TEXT!! AHHH.
		
		_twitter = new TwitterNet(_username, _password);
		_twitter.ClientName = "twitalot";
		_twitter.LoggedIn += HandleLoggedIn;
		_twitter.LoginAsync();	
	}

	void HandleLoggedIn(User user)
	{
		Application.Invoke(delegate {
			
			lblTweet.Text = user.Tweet.Text;
			
			btnUpdate.Sensitive = true;
		
			this.Title = "twitalot";	//TODO: Setup app name variable.
			this.Title = string.Format("{0} | {1} ({2})", this.Title, user.ScreenName, user.StatusesCount);
			this.Title = string.Format("{0} | {1}", this.Title, _twitter.RetrieveRateLimitStatus());
			
			Notifications.Notification notify = new Notifications.Notification(string.Format("@{0}", user.ScreenName), user.Tweet.Text, this.Icon);
			notify.Show();		
			
			GetFriendsTimeLine();
			
			hbLogin.Visible = false;
			lblTweet.Visible = true;
		});		
	}
	
	private void GetFriendsTimeLine()
	{
		
		string sinceID = string.Empty;
		if(_tweets.Count > 0)
			sinceID = _tweets[0].Id.ToString();
		
		TweetCollection newTweets = _twitter.GetFriendsTimeline(sinceID);
		
		if(newTweets.Count == 1)
			new Notifications.Notification(string.Format("@{0}", newTweets[0].User.ScreenName), newTweets[0].Text, this.Icon).Show();
		else
			new Notifications.Notification("Twitalot", string.Format("{0} new tweets", newTweets.Count), this.Icon).Show();
		
		newTweets.AddRange(_tweets); //append old tweets to new tweets;
		
		_tweets = newTweets;
		
		Console.WriteLine("Tweets: {0}", _tweets.Count);
		DisplayTweets(_tweets);	
	}
	
	private void DisplayTweets(TweetCollection tweets)
	{
		VBox box = new VBox(false, 0);
		
		int i = 0;
		foreach(Tweet tweet in tweets)
		{
			bool alt = (i++ % 2 != 0);
					
			twitalotgtk.TweetDisplay td = new twitalotgtk.TweetDisplay(tweet, alt);
			
			box.PackStart(td);
		}
		
		scrolledwindow1.AddWithViewport(box);
		this.ShowAll();
	}

	protected virtual void OnPreferencesActionActivated (object sender, System.EventArgs e)
	{
		PreferencesWindow pw = new PreferencesWindow();
		pw.Show();
	}
}